package main

import (
	"log"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	hunyuan "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/hunyuan/v20230901"
)

func main() {
	// 导入.env文件的配置
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	r := gin.Default()
	r.Use(Cors)

	// 添加路由组
	aiTranslator := r.Group("/ai-translator")
	{
		aiTranslator.POST("/chatTranslations", chatTranslations)
	}

	// 添加静态文件服务，将前端文件直接通过Go服务器提供
	r.Static("/ai-translator", "../fronted")

	r.Run(":8090")
}

// Cors 跨域中间件
func Cors(c *gin.Context) {
	c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
	c.Writer.Header().Set("Access-Control-Allow-Headers", "*")
	c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
	c.Next()
}

// chatTranslations 翻译
func chatTranslations(c *gin.Context) {
	// 获取请求参数
	text := c.PostForm("text")
	source := c.PostForm("source")
	target := c.PostForm("target")
	log.Printf("请求翻译内容: %s\n", text)

	// 获取环境变量
	secretId := os.Getenv("HUNYUAN_SECRET_ID")
	secretKey := os.Getenv("HUNYUAN_SECRET_KEY")
	if secretId == "" || secretKey == "" {
		c.JSON(500, gin.H{
			"error": "server's API secretId or secretKey is empty",
		})
		return
	}

	// 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
	// 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
	// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
	credential := common.NewCredential(
		secretId,
		secretKey,
	)
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "hunyuan.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := hunyuan.NewClient(credential, "ap-beijing", cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := hunyuan.NewChatTranslationsRequest()

	request.Model = common.StringPtr("hunyuan-translation")
	request.Text = common.StringPtr(text)
	request.Source = common.StringPtr(source)
	request.Target = common.StringPtr(target)

	// 返回的resp是一个ChatTranslationsResponse的实例，与请求对象对应
	response, err := client.ChatTranslations(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		log.Printf("An API error has returned: %s", err)
		c.JSON(500, gin.H{
			"error": err,
		})
		return
	}
	if err != nil {
		panic(err)
	}
	// 输出json格式的字符串回包
	if response.Response != nil {
		// 非流式响应
		log.Printf(response.ToJsonString())
		c.JSON(200, gin.H{
			"data": response.Response.Choices[0].Message.Content,
		})
	} else {
		// 流式响应
		for event := range response.Events {
			log.Printf(string(event.Data))
		}
	}
}
